package com.kehutong.payfees.util;

import com.kehutong.payfees.entity.ChargeBillItem;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import org.coraframework.boot.Application;
import org.coraframework.config.Config;

import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;

/**
 * @program: kht
 * @description:
 * @author: joneron
 * @create: 2021/6/1
 **/
public class PdfTableUtil {

    /**
     * 生成PDF表格
     * @param mapParam
     * @param font
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Table createTable3(Map<String,Object> mapParam, Font font) throws DocumentException, IOException {

        //创建一个有3列的表格
        Table table = new Table(8,4);
        table.setWidth(100); //表格站table 100%
        table.setWidths(new int[]{5,15,25,10,10,10,10,15}); //每列比例
        table.setTableFitsPage(true);//防止跨页有段开的边框（填充整页）
        table.setBorderWidth(1);
        table.setBorderColor(new Color(0, 0, 0));
        table.setPadding(5);
        //开启可变化边框
        table.setUseVariableBorders(true);
        // 添加此代码后每页都会显示表头
        table.endHeaders();
        //table.setSpacing(5);

        // 创建表头
        Cell cell1 = setTableHeader("序号");
        Cell cell2 = setTableHeader("收费项");
        Cell cell3 = setTableHeader("摘要");
        Cell cell4 = setTableHeader("上月读数");
        Cell cell5 = setTableHeader("本月读数");
        Cell cell6 = setTableHeader("数量");
        Cell cell7 = setTableHeader("单价");
        Cell cell8 = setTableHeader("金额");
        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);
        table.addCell(cell5);
        table.addCell(cell6);
        table.addCell(cell7);
        table.addCell(cell8);

        List<ChargeBillItem> receiptInfos = (List<ChargeBillItem>)mapParam.get("dataList");

        int sizeList = receiptInfos.size();

        for (int i = 0; i < sizeList ; i++) {

            ChargeBillItem receiptInfo = receiptInfos.get(i);
            Cell celli1 = setTableBody(""+(i+1),font);
            Cell celli2 = setTableBody(receiptInfo.getName(),font);
            Cell celli3 = setTableBody(resultStr(mapParam.get("content")),font);
            Cell celli4 = setTableBody(reBigDec(receiptInfo.getLastReadNumber()),font);
            Cell celli5 = setTableBody(reBigDec(receiptInfo.getTheReadNumber()),font);
            Cell celli6 = setTableBody(reBigDec(receiptInfo.getAmount()),font);
            Cell celli7 = setTableBody(reBigDec(receiptInfo.getUnitPrice()),font);
            Cell celli8 = setTableBody(reBigDec(receiptInfo.getSubTotal()),font);
            table.addCell(celli1);
            table.addCell(celli2);
            table.addCell(celli3);
            table.addCell(celli4);
            table.addCell(celli5);
            table.addCell(celli6);
            table.addCell(celli7);
            table.addCell(celli8);
        }

        //条数不够再生成几条,为了控制表格固定高度
        if(sizeList < 10){
            int num = 10 - sizeList;
            for (int i = 0; i < num; i++) {
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
                table.addCell(setTableBody("",font));
            }
        }

        Cell celli9 = setTableHeader("合计（小写）",12,Color.RED,Element.ALIGN_LEFT);
        String total = reBigDec(new BigDecimal(mapParam.get("totalAmount").toString()));
        Cell celli10 = setTableHeader("￥"+total,12,Color.BLACK,Element.ALIGN_LEFT);
        celli9.setColspan(2); //跨行
        table.addCell(celli9);
        celli10.setColspan(6); //跨行
        table.addCell(celli10);

        Cell celli11 = setTableHeader("合计人民币（大写）",12,Color.RED,Element.ALIGN_LEFT);
        Cell celli12 = setTableHeader(MoneyUtil.showMoney(Double.parseDouble(total)),12,Color.BLACK,Element.ALIGN_LEFT);
        celli11.setColspan(2); //跨行
        table.addCell(celli11);
        celli12.setColspan(6); //跨行
        table.addCell(celli12);

        if(mapParam.get("type").equals("payBill")){
            Cell celli13 = setTableHeader("说明",12,Color.BLACK,Element.ALIGN_LEFT);
            Cell celli14 = setTableHeader(mapParam.get("remark").toString(),10,Color.BLACK,Element.ALIGN_LEFT);
            celli13.setColspan(1); //跨行
            table.addCell(celli13);
            celli14.setColspan(7); //跨行
            table.addCell(celli14);
        }

        return table;

    }

    /**
     * 动态设置
     * @param name
     * @param fontSize
     * @param color
     * @param element  Element.ALIGN_CENTER
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Cell setTableHeader(String name,int fontSize,Color color,int element) throws DocumentException, IOException {

        Cell cell = new Cell(new Phrase(name,setFonts(fontSize,color)));
        //单元格水平对齐方式
        cell.setHorizontalAlignment(element);
        //单元格垂直对齐方式
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        //cell.setHeader(true);
        //cell.setBackgroundColor(Color.RED);
        cell.setBorderColor(Color.PINK);

        return cell;
    }

    /**
     * 设置cell
     * @param name
     * @return
     * @throws BadElementException
     */
    public static Cell setTableHeader(String name) throws DocumentException, IOException {

        Cell cell = new Cell(new Phrase(name,setFonts(12,Color.RED)));
        //单元格水平对齐方式
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //单元格垂直对齐方式
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        //cell.setHeader(true);
        //cell.setBackgroundColor(Color.RED);
        cell.setBorderColor(Color.PINK);

        return cell;
    }

    /**
     * 设置cell
     * @param name
     * @return
     * @throws BadElementException
     */
    public static Cell setTableBody(String name,Font font) throws BadElementException{

        Cell cell = new Cell(new Phrase(name,font));
        //单元格水平对齐方式
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //单元格垂直对齐方式
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        //开启可变边框
        cell.setUseVariableBorders(true);
        cell.setHeader(true);
        cell.setBorderColorLeft(Color.PINK);
        cell.setBorderColorRight(Color.PINK);
        cell.setBorderColorTop(Color.WHITE);
        cell.setBorderColorBottom(Color.WHITE);

        return cell;
    }

    /**
     * 设置相关参数
     * @param document
     * @return
     */
    public static Document setParameters(Document document,String title,String subject,String keywords,String author,
                                         String creator){
        // 设置标题
        document.addTitle(title);
        // 设置主题
        document.addSubject(subject);
        // 设置作者
        document.addKeywords(keywords);
        // 设置作者
        document.addAuthor(author);
        // 设置创建者
        document.addCreator(creator);
        // 设置生产者
        document.addProducer();
        // 设置创建日期
        document.addCreationDate();

        return document;
    }

    /**
     * 设置字体大小
     * @param size
     * @param color
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Font setFonts(int size,Color color) throws DocumentException, IOException {

        BaseFont bfChinese = null;

        String osName = System.getProperties().getProperty("os.name").toLowerCase();

        if (osName.contains("linux")) {
            Config config = Application.getConfig("web");
            String fontUrl = config.getString("font_url")+"simsun.ttc,1";
            bfChinese = BaseFont.createFont(fontUrl,BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
        } else {
            bfChinese = BaseFont.createFont(
                    System.getProperty("user.dir")+"\\pay-payfees\\src\\main\\webapp\\WEB-INF\\doc\\simsun.ttc,1",
                    BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
        }

          //创建常用字体
        return new Font(bfChinese, size, Font.NORMAL,color);
    }

    public static String resultStr(Object obj){
        if(null == obj){
            return "--";
        }
        return obj.toString();
    }

    public static String reBigDec(BigDecimal obj){
        if(null == obj){
            return "0.00";
        }
        return new BigDecimal(obj+"").setScale(2, BigDecimal.ROUND_UP).toString();
    }

    /**
     * 生成方式： 前缀 + 13位时间戳
     * @param prefix
     * @return
     */
    public static String generateNumber(String prefix){

        return prefix + System.currentTimeMillis();
    }

}
